<template>
	<view>
		<scroll-view id="scrollWrap" :style="`height: ${scollHeight}`" :scroll-y="scrollView" @scrolltolower="scrolltolower" class="scroll-list" >
			<view class="list">
				<template>
					<slot :item="item" :index="index" v-for="item, index in list"></slot>
				</template>
			</view>
			<view :class="['cu-load', isLoadEnd ? 'over' : 'loading'].concat(loadCls)" v-show="isPager && toBottom"></view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		props: {
			api: {
				type: String,
				default() {
					return ''
				}
			},
			scrollView: {
				type: Boolean,
				default() {
					return false
				}
			}, // 是否scroll-view滚动
			showLoading: {
				type: Boolean,
				default () {
					return true
				}
			}, // 是否展示加载中
			loadCls: {
				type: String | Array,
				default () {
					return []
				}
			},
			isPager: {
				type: Boolean,
				default () {
					return true // 是否支持分页
				}
			}, // 是否支持分页
			pageNum: {
				type: Number,
				default () {
					return 10 // 分页条数
				}
			},
		},
		data() {
			return {
				list: [],
				page: 1,
				toBottom: false, // 是否滚动到底部
				scollHeight: 'auto', // 滚动容器高度
				isLoad: false, // 是否正在加载
				isLoadEnd: false, // 是否加载完成
			}
		},
		created() {
			if (this.showLoading) {
				uni.showLoading({
					title: '加载中...'
				})
			}
			this.getList()
		},
		mounted() {
			// 动态设置scrollheight，如果是局部滚动就需要设置
			if (this.scrollView) {
				const that = this
				uni.getSystemInfo({
					success: function(res) {
						const winH = res.windowHeight
						uni.createSelectorQuery().select(`#scrollWrap`).boundingClientRect(function(data) {
							that.scollHeight = winH - data.top + 'px'
						})
						.exec();
					},
				});
			}
		},
		methods: {
			reachBottom() {
				if (this.isLoad || this.isLoadEnd) {return}
				this.toBottom = true
				this.page++
				this.getList()
			},
			scrolltolower() {
				// 如果分页，滚动加载
				if (this.isPager && this.scrollView) {
					this.reachBottom()
				}
			},
			// 刷新列表
			refresh() {
				this.list = []
				this.page = 1
				uni.showLoading({
					title: '加载中...'
				})
				this.getList()
			},
			async getList() {
				this.isLoad = true
				let pageStr = ''
				if (this.isPager) {
					pageStr = `${this.page},${this.pageNum}`
				} else {
					pageStr = false
				}
				let data = await this.$es.req(this.$es.api[this.api], [{}, pageStr])
				setTimeout(() => {
					this.isLoad = false
					let list = []
					this.list = this.list.concat(list)
					if (list.length) {
						// 加载完成
						this.isLoadEnd = true
					} else {
						this.isLoadEnd = false
					}
					if (this.showLoading) {
						uni.hideLoading()
					}
				}, 2000)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.scroll-list {
		height: 100%;
	}
</style>
